﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Yz.Base;
using Yz.Base.ParaModels;
using Yz.Core.Extensions;
using Yz.Core.Tools;

namespace Yz.FileService.Middlewares
{
    /// <summary>
    /// 删除接口
    /// </summary>
    public class DeleteMiddleware : BaseUploadMiddleware, IMiddleware
    {
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            context.Response.ContentType = "application/json; charset=utf-8";
            #region 跨域上传
            if (context.Request.Method.Equals(HttpMethods.Options, StringComparison.OrdinalIgnoreCase))
            {
                base.AddHttpOptionHeader(context);
            }
            #endregion

            #region 后台post上传
            else if (context.Request.Method.Equals(HttpMethods.Post, StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    #region 验证token
                    await ValidateTokenAsync(context);
                    context.Request.Headers.TryGetValue("appId", out StringValues appId);
                    #endregion

                    StringValues sv = context.Request.Form["application/json"];
                    if (sv == StringValues.Empty)
                    {
                        sv = context.Request.Form["data"];
                    }
                    string fileId = "";
                    if (sv != StringValues.Empty)
                    {
                        var paraFileId = JsonConvert.DeserializeObject<ParaFileId>(sv);
                        if (paraFileId == null || string.IsNullOrEmpty(paraFileId.Id))
                        {
                            await context.Response.WriteAsync(new VmUpFileBase()
                            {
                                msg = "参数不正确！"
                            }.ToJson());
                            return;
                        }
                        fileId = paraFileId.Id;
                    }
                    string filePath = _uploadConfig.PhysicalPath + fileId.ToDes3Decrypt();

                    if (!filePath.Contains(appId))
                    {
                        await context.Response.WriteAsync(new VmUpFileBase()
                        {
                            msg = "您没有权限删除此文件！"
                        }.ToJson());
                        return;
                    } 
                    if (!File.Exists(filePath))
                    {
                        await context.Response.WriteAsync(new VmUpFileBase()
                        {
                            msg = "您要删除的文件不存在！"
                        }.ToJson());
                        return;
                    }
                    File.Delete(filePath);
                    await context.Response.WriteAsync(new VmUpFileBase()
                    {
                        msg = "文件删除成功！"
                    }.ToJson());
                    return;
                }
                catch (Exception ex)
                {
                    YzNLog.Error(ex);
                    await context.Response.WriteAsync(new VmUpFileBase()
                    {
                        msg = "文件删除失败"
                    }.ToJson());
                }
            }
            #endregion

            #region 非法上传
            else
            {
                await base.AddHttpNotAllowedAsync(context);
            }
            #endregion 
        }
    }
}
